package com.icodingedu.springcloud.config;

import com.icodingedu.springcloud.filter.AuthFilter;
import com.icodingedu.springcloud.filter.ErrorFilter;
import com.icodingedu.springcloud.filter.TimerFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

@Configuration
public class GatewayConfiguration {

//    @Autowired
//    private TimerFilter timerFilter;

    @Autowired
    private AuthFilter authFilter;

    @Autowired
    private ErrorFilter errorFilter;

    @Autowired
    private KeyResolver hostNameResolver;

    @Autowired
    @Qualifier("redisLimiterUser")
    private RateLimiter rateLimiterUser;

    @Bean
    @Order
    public RouteLocator customerRoutes(RouteLocatorBuilder builder){
        LocalDateTime ldt1 = LocalDateTime.of(2020,4,12,22,6,30);
        LocalDateTime ldt2 = LocalDateTime.of(2020,4,12,23,6,35);
        return builder.routes()
                .route(r -> r.path("/gavinjava/**")
                        .and().method(HttpMethod.GET)
//                        .and().header("name")
                        .filters(f -> f.stripPrefix(1)
                            .addResponseHeader("java-param","gateway-config")
//                            .filter(timerFilter)
//                            .filter(authFilter)
                            .filter(errorFilter)
                            .requestRateLimiter(
                                c -> {
                                    c.setKeyResolver(hostNameResolver);
                                    c.setRateLimiter(rateLimiterUser);
                                })
                        )
                        .uri("lb://FEIGN-CLIENT")
                )
                .route(r -> r.path("/secondkill/**")
                        //.and().after(ZonedDateTime.of(ldt, ZoneId.of("Asia/Shanghai")))
                        .and().between(ZonedDateTime.of(ldt1, ZoneId.of("Asia/Shanghai")),ZonedDateTime.of(ldt2, ZoneId.of("Asia/Shanghai")))
                        .filters(f -> f.stripPrefix(1))
                        .uri("lb://FEIGN-CLIENT")
                )
                .build();
    }
}
